package com.wgj.android.zfp;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jiaai.xui.XUI;
import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.utils.http.BaseHttpCallBack;
import com.wgj.android.base.WGJApplication;
import com.wgj.android.entity.Friend;
import com.wgj.android.entity.Group;
import com.wgj.android.entity.WeiXingGroup;
import com.wgj.android.http.WeiXinEvents;
import com.wgj.android.http.weixin.WXFormatUtil;
import com.wgj.android.http.weixin.WXHttp;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.http.weixin.event.ContactEvent;
import com.wgj.android.http.weixin.model.BaseRequest;
import com.wgj.android.http.weixin.model.WXFriend;
import com.wgj.android.http.weixin.model.WXInfo;
import com.wgj.android.http.weixin.model.WxGroupBody;
import com.wgj.android.http.weixin.model.WxGroupBodySub;
import com.wgj.android.utils.FileUtil;
import com.wgj.android.utils.MD5Util;

import org.greenrobot.eventbus.EventBus;




import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Response;

/**
 * Created by Administrator on 2017/11/27.
 */

public class GetWXFriendService extends Service {
    private static GetWXFriendService service;
    private FileUtil fileUtil;
    private  Group root;
    private  ArrayList<String> chatGroups=new ArrayList<>();

    private List<WXFriend> wxFriends = new ArrayList<>();
    private  boolean isStop=false;
    private static int currNum=1;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.service=this;
        fileUtil=new FileUtil("wgj");
       try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        getRun("0");
                    } catch (Exception e) {
                        e.printStackTrace();
                        stopSelf();
                    }

                }
            }).start();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.service=null;
        currNum=1;
    }


    private void getRun(final String Seq) throws Exception {
            WeiXinCacheUtil.saveStatus(WeiXinEvents.EventsType.GETINGCONTACT);
            final WXInfo wxInfo = WeiXinCacheUtil.getInfo();
            String url = "http://" + wxInfo.getBaseUrl() + "/cgi-bin/mmwebwx-bin/webwxgetcontact?" +
                    "r=".concat("" + new Date().getTime()) +
                    "&seq=".concat(Seq) +
                    "&skey=".concat(wxInfo.getSkey());
            String res = WXHttp.obtain().syncPost(url, "{}");
            JSONObject jsonObject =JSONObject.parseObject(res);
            wxFriends .addAll(WXFormatUtil.getAllName(jsonObject, wxInfo));


            String temp = jsonObject.get("Seq").toString();
            if (!"0".equals(temp)) {
                getRun(temp);
            } else {
                new Thread(new saveFriendRunnable(wxFriends)).start();
            }

        }

    private class saveFriendRunnable implements Runnable {
            private List<WXFriend> friends;

            private List<Friend> newsFriends = new ArrayList<>();

            public saveFriendRunnable(List<WXFriend> friends) {
                this.friends = friends;
            }

            @Override
            public void run() {
                final WXInfo wxInfo = WeiXinCacheUtil.getInfo();
                BaseRequest baseRequest = new BaseRequest();
                baseRequest.setDeviceID("e" + (WXFormatUtil.getRand15Num()));
                baseRequest.setSid(wxInfo.getWxsid());
                baseRequest.setSkey(wxInfo.getSkey());
                baseRequest.setUin(Long.parseLong(wxInfo.getWxuin()));
                String getGroupUrl = "http://".concat(wxInfo.getBaseUrl())
                        .concat("/cgi-bin/mmwebwx-bin/webwxbatchgetcontact?type=ex&r="+new Date().getTime());
                Gson gson = new Gson();
                ArrayList <WeiXingGroup> weiXingGroups=new ArrayList<>();
                ArrayList<WXFriend> arrayList=new ArrayList<>();
                for (final WXFriend f : friends) {
                    WxGroupBody wxGroupBody = new WxGroupBody();
                    wxGroupBody.setBaseRequest(baseRequest);
                    List<WxGroupBodySub> wxGroupBodySubs = new ArrayList<>();

                    wxGroupBody.setList(wxGroupBodySubs);
                    String s = f.getNickName();
                    s = s.replaceAll("<span class=\"emoji emoji", "[")
                            .replaceAll("\"></span>", "]");
                    f.setNickName(s);
                    //群数量获取

                    if (f.getUserName().contains("@@")) {
                        XCache.get(XUI.getContext()).put(MD5Util.encrypt(f.getNickName()), f.getUserName());
                        wxGroupBodySubs.add(new WxGroupBodySub(f.getUserName()));

                        chatGroups.add(f.getNickName());
                        try {
                            String body=WXHttp.obtain().syncPost(getGroupUrl,gson.toJson(wxGroupBody));
                            JSONObject object=JSONObject.parseObject(body);
                            if(object.getJSONObject("BaseResponse").getIntValue("Ret")==0){
                                if(object.containsKey("ContactList")){
                                    WeiXingGroup weiXingGroup = new WeiXingGroup();
                                    weiXingGroup.set_Id(f.getUserName());
                                    weiXingGroup.setNickName(f.getNickName());
                                    weiXingGroup.setUuId(wxInfo.getWxuin());
                                    weiXingGroup.setNumber(object.getJSONArray("ContactList").getJSONObject(0).getIntValue("MemberCount"));
                                    weiXingGroups.add(weiXingGroup);
                                }
                            }else {
                                Thread.sleep(3000);
                            }
                        } catch (Exception e) {
                             e.printStackTrace();
                        }

                    } else {
                        arrayList.add(f);
                    }
                    //获取头像// todo
                    final String filePath="weixing"+ File.separator+wxInfo.getWxuin()+File.separator;
                    final String fileName=MD5Util.encrypt(f.getNickName());
                    if (!fileUtil.isFileExist(filePath+fileName)){
                        String getImUrl = "https://".concat(wxInfo.getBaseUrl()).concat(f.getHeadImgUrl());
                        WXHttp.obtain().bytePost(getImUrl, null, new BaseHttpCallBack() {
                            @Override
                            public void onSuccess(Response response) throws IOException {
                                InputStream in=response.body().byteStream();
                                fileUtil.write2SDFromInput(filePath,fileName,in);
                            }

                            @Override
                            public void onFailed(int i, String s, boolean b) {

                            }
                        });
                    }

                }
                WeiXinCacheUtil.saveWeiXinGroup(wxInfo.getWxuin(),weiXingGroups);
                WeiXinCacheUtil.saveChatGroup(wxInfo.getWxuin(), chatGroups);
                WeiXinCacheUtil.saveFriends(wxInfo.getWxuin(),arrayList);
                EventBus.getDefault().post(new ContactEvent(0, 0));//发送通讯录进度报告
                stopSelf();
            }


        }

    public static void stop(){
        service.stopSelf();
    }
}


